const result = {
  /**
   * joinMemberSuccess:入会成功;
   * joinMemberCancle:入会取消;
   * joinMemberFail:入会失败;
   * alreadyMember:已是会员;
   */
  status: "joinMemberSuccess",
  message: "",
  originData: {},
  errMsg: "",
};
Component({
  data: {
    showNewMember: false,
    isMember: false,
  },
  properties: {
    shopId: String,
    styles: String,
    showOldButton: Boolean, //使用老版入会
  },

  lifetimes: {
    attached: async function () {
      const info = tt.getSystemInfoSync();
      const version = info.version.split(".");
      if (Number(version[0]) > 23 || (Number(version[0]) === 23 && Number(version[1]) >= 8)) {
        this.setData({
          showNewMember: this.data.showOldButton ? false : true,
        });
      }
      const checkRes = await this.checkShopMemberAsync(this.data.shopId);
      if (checkRes.status) {
        this.setData({
          isMember: true,
        });
        result.status = "alreadyMember";
        result.message = "已是会员";
        this.send();
      }
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  methods: {
    send() {
      this.triggerEvent("onchange", {
        ...result,
      });
    },
    handleJoinMemberSuccess(e) {
      result.status = "joinMemberSuccess";
      result.message = "入会成功";
      result.originData = e.detail;
      this.send();
    },
    handleJoinMemberCancel(e) {
      result.status = "joinMemberCancle";
      result.message = "入会取消";
      result.originData = e.detail;
      this.send();
    },
    handleJoinMemberError(e) {
      const { errMsg, errNo } = e.detail;
      if (errNo === 21606) {
        result.status = "alreadyMember";
        result.message = "已是会员";
      } else {
        result.status = "joinMemberFail";
        result.message = "入会失败";
      }
      result.errMsg = errMsg;
      result.originData = e.detail;
      this.send();
    },
    checkShopMemberAsync(shopId) {
      return new Promise((resolve, reject) => {
        tt.checkShopMember({
          shopId: shopId,
          success(res) {
            resolve({
              stauts: true,
              isMember: res.isMember,
            });
          },
          fail(res) {
            resolve({
              stauts: false,
              isMember: res,
            });
          },
        });
      });
    },
  },
});
